package cs340.stormtroopers.junitTests;

import java.util.Random;

import cs340.stormtroopers.hypeerweb.Contents;
import cs340.stormtroopers.hypeerweb.HyPeerWeb;
import cs340.stormtroopers.hypeerweb.Node;
import cs340.stormtroopers.hypeerweb.Parameters;
import cs340.stormtroopers.hypeerweb.BroadcastVisitor;
import junit.framework.TestCase;

public class SimpleBroadcastTest extends TestCase
{
	private final int HYPEERWEB_SIZE = 100;

	private void simpleTest()
	{
		HyPeerWeb hypeerweb = HyPeerWeb.getSingleton();
		Node startNode = new Node(0);
		hypeerweb.addToHyPeerWeb(startNode, null);

		BroadcastVisitor v = new ConcreteBroadcastVisitor();
		Parameters p = v.createInitialParameters();
		String msg = "Contains no MSG";
		p.set("message", msg);
		startNode.accept(v, p);

		Contents c = startNode.getContents();
		assertTrue(c.containsValue(msg));
	}

	public void testBroadcast()
	{
		simpleTest();

		HyPeerWeb hypeerweb = HyPeerWeb.getSingleton();
		Node startNode = new Node(0);
		hypeerweb.addToHyPeerWeb(startNode, null);

		// Building HyPeerWeb
		for (int c = 1; c < HYPEERWEB_SIZE; ++c)
		{
			System.out.print(c + " ");
			if (c % 10 == 0)
				System.out.println();

			hypeerweb.addToHyPeerWeb(new Node(c), startNode);

			for (int i = c - 1; i >= 0; --i)
			{
				Node temp = hypeerweb.getNode(i);
				String msg = "Message " + i + c;

				BroadcastVisitor v = new ConcreteBroadcastVisitor();
				Parameters p = v.createInitialParameters();
				p.set("message", msg);

				temp.accept(v, p);

				allNodesHaveMessage(hypeerweb, c, msg);
			}
		}
		System.out.println();

		largeTest();
	}

	private void largeTest()
	{
		HyPeerWeb hypeerweb = HyPeerWeb.getSingleton();
		Node startNode = new Node(0);
		hypeerweb.addToHyPeerWeb(startNode, null);
		int NODES = 5000;
		for (int c = 1; c <= NODES; ++c)
			hypeerweb.addToHyPeerWeb(new Node(c), startNode);
		System.out.println();

		Random r = new Random();
		for (int i = 0; i < 10; i++)
		{
			Node n = hypeerweb.getNode(r.nextInt(NODES));
			System.out.print(n.getWebIdValue()+" ");
			BroadcastVisitor v = new ConcreteBroadcastVisitor();
			Parameters p = v.createInitialParameters();
			String msg = "BIGGUN "+i;
			p.set("message", msg);
			n.accept(v, p);
			
			allNodesHaveMessage(hypeerweb, NODES, msg);
		}
		
		System.out.println("\nDONE !  " + NODES);
	}

	private void allNodesHaveMessage(HyPeerWeb h, int c, String msg)
	{
		System.out.println(msg);
		for (int i = 0; i < c; ++i)
		{
			Node n = h.getNode(i);
			assertTrue(n.getContents().containsValue(msg));
		}
	}
}
